import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from PIL import Image, ImageTk
import threading
import zhiwenyi 
import os
import time
import control 
import match
from datetime import datetime
app=None
tmpimage='tmp/fingerprint_image.bmp'

# 设置图片
def setImage(path):
    new_image = Image.open(path)
    new_image = new_image.resize((200, 300), Image.ANTIALIAS)
    new_photo = ImageTk.PhotoImage(new_image)
    app.label.config(image=new_photo)
    # 保存对新图片的引用，避免被垃圾回收机制销毁
    app.label.image = new_photo

def change():
    # print('change ')
    while True:
        if os.path.exists(tmpimage):
            setImage(tmpimage)
        time.sleep(1.5)
        # if os.path.exists(tmpimage):
        #     os.remove(tmpimage)


class EmployeeAttendanceSystem:
    def __init__(self, master):
        self.master = master
        self.master.title("员工指纹考勤管理系统")
        self.master.geometry("800x600")

        self.create_widgets()



    def cleanup(self):
        if messagebox.askokcancel("关闭窗口", "确定要关闭窗口吗？"):
            zhiwenyi.closefinger()
            self.master.destroy()


    def create_widgets(self):
        # 创建顶部标题
        self.title_label = tk.Label(self.master, text="员工指纹考勤系统", font=("Helvetica", 20))
        self.title_label.pack(pady=10)

        # 创建左侧菜单框架
        self.menu_frame = tk.Frame(self.master, width=400,bd=2, relief=tk.GROOVE)
        self.menu_frame.pack(side=tk.LEFT, fill=tk.Y, padx=10, pady=10)

        # 创建右侧内容框架
        self.content_frame = tk.Frame(self.master, bd=2, relief=tk.GROOVE)
        self.content_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 创建菜单按钮
        self.employee_info_button = tk.Button(self.menu_frame, text="员工信息", command=self.employee_info_entry)
        self.employee_info_button.pack(pady=5)

        self.attendance_button = tk.Button(self.menu_frame, text="考勤打卡", command=self.attendance)
        self.attendance_button.pack(pady=5)

        self.attendance_summary_button = tk.Button(self.menu_frame, text="考勤统计", command=self.attendance_summary)
        self.attendance_summary_button.pack(pady=5)
        img = Image.open('指纹.jpg')
        img = img.resize((280, 355), Image.ANTIALIAS)  # 调整图像大小
        self.img_tk = ImageTk.PhotoImage(img)
        
        self.label = tk.Label(self.menu_frame, image=self.img_tk)
        self.label.pack(pady=10)


    def employee_info_entry(self):
        self.clear_content_frame()

        # 创建员工信息录入界面
        self.employee_info_label = tk.Label(self.content_frame, text="员工信息录入", font=("Helvetica", 16))
        self.employee_info_label.pack(pady=10)
        self.num_label = tk.Label(self.content_frame, text="编号:")
        self.num_label.pack()
        self.num_entry = tk.Entry(self.content_frame)
        self.num_entry.pack()

        self.name_label = tk.Label(self.content_frame, text="姓名:")
        self.name_label.pack()
        self.name_entry = tk.Entry(self.content_frame)
        self.name_entry.pack()

        self.age_label = tk.Label(self.content_frame, text="年龄:")
        self.age_label.pack()
        self.age_entry = tk.Entry(self.content_frame)
        self.age_entry.pack()

        self.gender_label = tk.Label(self.content_frame, text="性别:")
        self.gender_label.pack()
        self.gender_entry = tk.Entry(self.content_frame)
        self.gender_entry.pack()

        # self.fingerprint_label = tk.Label(self.content_frame, text="指纹录入:")
        # self.fingerprint_label.pack()
        # self.fingerprint_entry = tk.Entry(self.content_frame)
        # self.fingerprint_entry.pack()

        self.save_button = tk.Button(self.content_frame, text="保存", command=self.save_employee_info)
        self.save_button.pack(pady=10)

    def save_employee_info(self):
        name = self.name_entry.get()
        age = self.age_entry.get()
        gender = self.gender_entry.get()
        num = self.num_entry.get()

        if name and age and gender :
            # 保存员工信息（这里可以自行修改保存方式，比如保存到文件或数据库）
            data = {
            '编号': [num],
            '姓名': [name],
            '性别': [gender],
            '年龄': [age]}
            control.saveEmp(data)
            # 更改图片的目录和文件名
            os.rename(tmpimage, 'data/'+num+".bmp")
            messagebox.showinfo("成功", "员工信息已保存！")
        else:
            messagebox.showerror("错误", "请填写所有信息！")

    def attendance(self):
        self.clear_content_frame()
        # 创建考勤打卡界面
        self.attendance_label = tk.Label(self.content_frame, text="考勤打卡", font=("Helvetica", 16))
        self.attendance_label.pack(pady=10)


        img = Image.open('指纹.jpg')
        img = img.resize((280, 355), Image.ANTIALIAS)  # 调整图像大小
        self.img_tk = ImageTk.PhotoImage(img)
        
        self.label = tk.Label(self.content_frame, image=self.img_tk)
        self.label.pack(pady=10)


        # change_thread=threading.Thread(target=change)
        # change_thread.daemon=True
        # change_thread.start()
        self.name_label = tk.Label(self.content_frame, text='指纹打卡')
        self.name_label.pack()
        self.clock_button = tk.Button(self.content_frame, text="打卡", command=self.clock_in_out())
        self.clock_button.pack(pady=10)



    def clock_in_out(self):
        num=match.anymatch()
        print(num)
        emp=control.getEmp("编号",num.split('\\')[1].split('.')[0])
        print(emp)
        str1=''
        if(len(emp)>0):
            for key in emp[0].keys():
                print(key,emp[0][key])
                str1 =str1 +" "+ key+" : "+str(emp[0][key])
            str1=str1+"  打卡成功"
        else:
            str1="打卡失败"
        self.name_label.config(text=str1)
        
        # 记录数据
        data = {'员工编号': [emp[0]['编号']],
        '姓名': [emp[0]['姓名']],
        '打卡类别': ['上班打卡' if datetime.now().hour<12 else '下班打卡'],
        '打卡时间': [datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')]}
        control.savedata(data)



    def attendance_summary(self):
        self.clear_content_frame()

        # 创建考勤统计界面
        self.attendance_summary_label = tk.Label(self.content_frame, text="考勤统计", font=("Helvetica", 16))
        self.attendance_summary_label.pack(pady=10)

        # 创建表格
        self.tree = ttk.Treeview(self.content_frame, columns=("员工编号", "姓名", "打卡类别", "打卡时间"), show="headings")
        self.tree.heading("员工编号", text="员工编号")
        self.tree.heading("姓名", text="姓名")
        self.tree.heading("打卡类别", text="打卡类别")
        self.tree.heading("打卡时间", text="打卡时间")
        self.tree.pack(fill=tk.BOTH, expand=True)

        # 示例数据
        fake_attendance_data = control.alldata()

        for data in fake_attendance_data:
            self.tree.insert("", "end", values=data)

    def clear_content_frame(self):
        # 清空右侧内容框架
        for widget in self.content_frame.winfo_children():
            widget.destroy()

def main():
    root = tk.Tk()
    global app
    app = EmployeeAttendanceSystem(root)
    root.protocol("WM_DELETE_WINDOW", app.cleanup)
    # # 启动线程
    app.thread = threading.Thread(target=zhiwenyi.fingerprint)
    app.thread.daemon = True
    app.thread.start()

    change_thread=threading.Thread(target=change)
    change_thread.daemon=True
    change_thread.start()
    root.mainloop()

if __name__ == "__main__":
    main()



